package com.reliable.service.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reliable.api.dto.keyword.KeywordDTO;
import com.reliable.api.param.keyword.KeywordAddParam;
import com.reliable.api.param.keyword.KeywordEditParam;
import com.reliable.api.param.keyword.KeywordParam;
import com.reliable.api.param.IdParam;
import com.reliable.common.core.domain.AjaxResult;
import com.reliable.service.domain.ReliableKeyword;
import com.reliable.service.service.IReliableKeywordService;
import com.reliable.service.utils.IdEncryptUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 关键词库Controller
 */
@Api(tags = "关键词库管理")
@Validated
@RestController
@RequestMapping("/reliable/keyword")
public class ReliableKeywordController {

    @Autowired
    private IReliableKeywordService reliableKeywordService;

    /**
     * 查询关键词列表
     */
    @ApiOperation("查询关键词列表")
    @PostMapping("/list")
    public AjaxResult list(@RequestBody(required = false) KeywordParam keywordParam) {
        // 设置分页参数
        int pageNum = (keywordParam != null && keywordParam.getPageNum() != null) ? keywordParam.getPageNum() : 1;
        int pageSize = (keywordParam != null && keywordParam.getPageSize() != null) ? keywordParam.getPageSize() : 10;
        
        Page<ReliableKeyword> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<ReliableKeyword> queryWrapper = new LambdaQueryWrapper<>();
        
        if (keywordParam != null) {
            if (keywordParam.getKeywordText() != null && !keywordParam.getKeywordText().isEmpty()) {
                queryWrapper.like(ReliableKeyword::getKeywordText, keywordParam.getKeywordText());
            }
            if (keywordParam.getKeywordType() != null && !keywordParam.getKeywordType().isEmpty()) {
                queryWrapper.eq(ReliableKeyword::getKeywordType, keywordParam.getKeywordType());
            }
        }
        
        queryWrapper.select(ReliableKeyword::getId, ReliableKeyword::getKeywordText, ReliableKeyword::getKeywordType);
        IPage<ReliableKeyword> result = reliableKeywordService.page(page, queryWrapper);
        
        List<KeywordDTO> records = result.getRecords().stream().map(keyword -> {
            KeywordDTO dto = new KeywordDTO();
            BeanUtils.copyProperties(keyword, dto);
            // 对ID进行加密
            dto.setKeywordId(IdEncryptUtils.encrypt(keyword.getId()));
            return dto;
        }).collect(Collectors.toList());
        
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("records", records);
        resultMap.put("total", result.getTotal());
        resultMap.put("pageNum", result.getCurrent());
        resultMap.put("pageSize", result.getSize());
        resultMap.put("pages", result.getPages()); // 总页数
        
        return AjaxResult.success(resultMap);
    }

    /**
     * 获取关键词详细信息
     */
    @ApiOperation("获取关键词详细信息")
    @PostMapping(value = "/info")
    public AjaxResult getInfo(@Valid @RequestBody IdParam idParam) {
        // 对传入的加密ID进行解密
        Long decryptId = IdEncryptUtils.decrypt(idParam.getBusinessId());
        ReliableKeyword keyword = reliableKeywordService.getById(decryptId);
        if (keyword != null) {
            // 对返回的ID进行加密
            keyword.setId(null);
            return AjaxResult.success(keyword);
        } else {
            return AjaxResult.error("未找到该关键词");
        }
    }

    /**
     * 新增关键词
     */
    @ApiOperation("新增关键词")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody KeywordAddParam keywordAddParam) {
        ReliableKeyword keyword = new ReliableKeyword();
        BeanUtils.copyProperties(keywordAddParam, keyword);
        reliableKeywordService.save(keyword);
        // 返回新增数据的加密ID
        return AjaxResult.success("新增成功", IdEncryptUtils.encrypt(keyword.getId()));
    }

    /**
     * 修改关键词
     */
    @ApiOperation("修改关键词")
    @PostMapping("/edit")
    public AjaxResult edit(@Valid @RequestBody KeywordEditParam keywordEditParam) {
        Long keywordId = IdEncryptUtils.decrypt(keywordEditParam.getKeywordId());
        ReliableKeyword keyword = new ReliableKeyword();
        BeanUtils.copyProperties(keywordEditParam, keyword);
        keyword.setId(keywordId);
        boolean result = reliableKeywordService.updateById(keyword);
        // 对返回的ID进行加密
        return AjaxResult.success(result);
    }

    /**
     * 删除关键词
     */
    @ApiOperation("删除关键词")
    @PostMapping("/remove")
    public AjaxResult remove(@Valid @RequestBody IdParam idParam) {
        // 对传入的加密ID进行解密
        Long decryptId = IdEncryptUtils.decrypt(idParam.getBusinessId());
        boolean result = reliableKeywordService.removeById(decryptId);
        return AjaxResult.success(result ? "删除成功" : "删除失败");
    }
}